package com.yc.framework.service;

import com.yc.common.constant.CacheConstant;
import com.yc.common.constant.Constant;
import com.yc.common.constant.UserConstant;
import com.yc.common.core.domain.model.LoginUser;
import com.yc.common.core.redis.RedisCache;
import com.yc.common.exception.ServiceException;
import com.yc.common.exception.user.CaptchaException;
import com.yc.common.exception.user.CaptchaExpireException;
import com.yc.common.exception.user.UserNotExistsException;
import com.yc.common.exception.user.UserPasswordNotMatchException;
import com.yc.common.utils.MessageUtil;
import com.yc.common.utils.StringUtil;
import com.yc.framework.manager.AsyncManager;
import com.yc.framework.manager.factory.AsyncFactory;
import com.yc.framework.security.context.AuthenticationContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("sysLoginService")
public class SysLoginService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录验证
     *
     * @param email    用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String email, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(email, code, uuid);
        // 登录前置校验
        loginPreCheck(email, password);

        // 用户验证
        Authentication authentication = null;

        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email, password);
            AuthenticationContextHolder.setContext(authenticationToken);

            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);

        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager
                        .getInstance()
                        .execute(AsyncFactory.recordLogininfor(email,
                                Constant.Status.FAIL_MESSAGE,
                                MessageUtil.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager
                        .getInstance()
                        .execute(AsyncFactory.recordLogininfor(email,
                                Constant.Status.FAIL_MESSAGE, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        //AsyncManager.getInstance().execute(AsyncFactory.recordLogininfor(email,
                //Constant.Status.SUCCESS_MESSAGE, MessageUtil.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * @param email   邮箱
     * @param captcha 验证码
     * @param uuid    唯一标识
     * @return 结果
     */
    public void validateCaptcha(String email, String captcha, String uuid) {

        //从缓存获取验证码
        String verifyKey = CacheConstant.CAPTCHA_CODE_KEY + StringUtil.nvl(uuid, "");
        StringBuilder redisCaptcha = redisCache.getCacheObject(verifyKey);
        System.out.println(redisCaptcha.toString());

        if (captcha == null) {
            AsyncManager.getInstance().execute(AsyncFactory.recordLogininfor(email, Constant.Status.FAIL_MESSAGE, MessageUtil.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }

        redisCache.deleteObject(verifyKey);

        if (!captcha.equalsIgnoreCase(redisCaptcha.toString())) {
            AsyncManager.getInstance().execute(AsyncFactory.recordLogininfor(email, Constant.Status.FAIL_MESSAGE, MessageUtil.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }

    }

    /**
     * 登录前置校验
     * @param email    用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String email, String password) {
        // 用户名或密码为空 错误
        if (StringUtil.isEmpty(email) || StringUtil.isEmpty(password)) {
            AsyncManager.getInstance().execute(AsyncFactory.recordLogininfor(email, Constant.Status.FAIL_MESSAGE, MessageUtil.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstant.PASSWORD_MIN_LENGTH
                || password.length() > UserConstant.PASSWORD_MAX_LENGTH) {
            AsyncManager.getInstance().execute(AsyncFactory.recordLogininfor(email, Constant.Status.FAIL_MESSAGE, MessageUtil.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // TODO 更改为验证邮箱地址是否正确
        /*if (email.length() < UserConstant.USERNAME_MIN_LENGTH
                || email.length() > UserConstant.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constant.Status.FAIL_MESSAGE, MessageUtil.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }*/
    }
}
